var db = window.sqlitePlugin.openDatabase({
    name: 'my.db',
    location: 'default',
    androidDatabaseProvider: 'system'
});

export function init() {
    db.transaction(function (tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS code_table (code text, number integer,timestamp BIGINT)');
        //删除前一天数据
        var now = new Date();
        now.setHours(0, 0, 0, 0)
        var l = now.getTime()
        tx.executeSql('DELETE FROM code_table WHERE timestamp < ?', [l]);
    });
}

export function saveCode(code) {
    db.transaction(function (tx) {
        //先删除 再添加
        tx.executeSql('DELETE FROM code_table WHERE code = ?', [code.code]);
        tx.executeSql('INSERT INTO code_table (code, number, timestamp) VALUES (?,?,?)', [code.code, code.number, new Date().getTime()]);
    }, function (error) {
        console.log('Transaction ERROR: ' + error.message);
    }, function () {
        console.log('Populated database OK');
    });

}
export function getCode(id) {
    return new Promise((resolve, reject) => {
        db.transaction(function (tx) {
            tx.executeSql('SELECT * FROM code_table WHERE code = ?', [id], function (tx, res) {
                if (res.rows.length > 0) {
                    resolve(res.rows.item(0));
                } else {
                    resolve(null);
                }
            });
        }, (e) => {
            reject(e)
        });
    });
}